package com.ke.searchhouse.controller.admin;

import com.ke.searchhouse.base.DataTableResponse;
import com.ke.searchhouse.base.HouseOperation;
import com.ke.searchhouse.base.HouseStatus;
import com.ke.searchhouse.base.Response;
import com.ke.searchhouse.config.AliCloudConfig;
import com.ke.searchhouse.form.PhotoForm;
import com.ke.searchhouse.service.impl.TenantCloudUploadService;
import com.ke.searchhouse.dto.*;
import com.ke.searchhouse.entity.SupportAddress;
import com.ke.searchhouse.form.DatatableSearch;
import com.ke.searchhouse.form.HouseForm;
import com.ke.searchhouse.service.IAddressService;
import com.ke.searchhouse.service.IHouseService;
import com.ke.searchhouse.util.ServiceMultiResult;
import com.ke.searchhouse.util.ServiceResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    private TenantCloudUploadService uploadFileService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IHouseService houseService;

    @PostMapping("/houses")
    @ResponseBody
    public DataTableResponse houses(@ModelAttribute DatatableSearch searchBody) {
        ServiceMultiResult result = houseService.adminQuery(searchBody);

        DataTableResponse response = new DataTableResponse(Response.Status.SUCCESS);
        response.setData(result.getResult());
        response.setRecordsFiltered(result.getTotal());
        response.setRecordsTotal(result.getTotal());
        response.setDraw(searchBody.getDraw());

        return response;
    }


    @PostMapping(value = "/upload/photo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public Response uploadPhoto(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Response.ofStatus(Response.Status.NOT_VALID_PARAM);
        }

        Response response = uploadFileService.upload(file);
        if (response.getCode().equals(Response.Status.SUCCESS.getCode())) {
            PhotoForm photoForm = new PhotoForm();
            photoForm.setPath(AliCloudConfig.ALIYUN_FILE_PREFIX + response.getData());

            return Response.ofSuccess(photoForm);
        }

        return response;
    }

    @PostMapping("/add/house")
    @ResponseBody
    public Response saveHouse(@Valid @ModelAttribute("form-house-add") HouseForm houseForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new Response(HttpStatus.BAD_REQUEST.value(),
                    bindingResult.getAllErrors().get(0).getDefaultMessage(), null);
        }

        if (null == houseForm.getPhotos() || null == houseForm.getCover()) {
            return Response.ofMessage(HttpStatus.BAD_REQUEST.value(), "请上传图片");
        }

        Map<SupportAddress.Level, SupportAddressDTO> addressMap = addressService.
                findCityAndRegion(houseForm.getCityEnName(), houseForm.getRegionEnName());
        if (addressMap.keySet().size() != 2) {
            return Response.ofStatus(Response.Status.NOT_VALID_PARAM);
        }

        ServiceResult<HouseDTO> result = houseService.save(houseForm);
        if (result.isSuccess()) {
            return Response.ofSuccess(result.getResult());
        }

        return Response.ofSuccess(Response.Status.NOT_VALID_PARAM);
    }

    @GetMapping("/house/edit")
    public String houseEditPage(@RequestParam(value = "id") Long id, Model model) {

        if (id == null || id < 1) {
            return "404";
        }

        ServiceResult<HouseDTO> serviceResult = houseService.findCompleteOne(id);
        if (!serviceResult.isSuccess()) {
            return "404";
        }

        HouseDTO result = serviceResult.getResult();
        model.addAttribute("house", result);

        Map<SupportAddress.Level, SupportAddressDTO> addressMap = addressService.findCityAndRegion(result.getCityEnName(), result.getRegionEnName());
        model.addAttribute("city", addressMap.get(SupportAddress.Level.CITY));
        model.addAttribute("region", addressMap.get(SupportAddress.Level.REGION));

        HouseDetailDTO detailDTO = result.getHouseDetail();
        ServiceResult<SubwayDTO> subwayServiceResult = addressService.findSubway(detailDTO.getSubwayLineId());
        if (subwayServiceResult.isSuccess()) {
            model.addAttribute("subway", subwayServiceResult.getResult());
        }

        ServiceResult<SubwayStationDTO> subwayStationServiceResult = addressService.findSubwayStation(detailDTO.getSubwayStationId());
        if (subwayStationServiceResult.isSuccess()) {
            model.addAttribute("station", subwayStationServiceResult.getResult());
        }

        return "admin/house-edit";
    }


    /**
     * 编辑接口
     */
    @PostMapping("/house/edit")
    @ResponseBody
    public Response editHouse(@Valid @ModelAttribute("form-house-edit") HouseForm houseForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new Response(HttpStatus.BAD_REQUEST.value(), bindingResult.getAllErrors().get(0).getDefaultMessage(), null);
        }

        Map<SupportAddress.Level, SupportAddressDTO> addressMap = addressService.findCityAndRegion(houseForm.getCityEnName(), houseForm.getRegionEnName());

        if (addressMap.keySet().size() != 2) {
            return Response.ofSuccess(Response.Status.NOT_VALID_PARAM);
        }

        ServiceResult result = houseService.update(houseForm);
        if (result.isSuccess()) {
            return Response.ofSuccess(null);
        }

        Response response = Response.ofStatus(Response.Status.BAD_REQUEST);
        response.setMessage(result.getMessage());
        return response;
    }

    /**
     * 移除图片接口
     * @param id
     * @return
     */
    @DeleteMapping("/house/photo")
    @ResponseBody
    public Response removeHousePhoto(@RequestParam(value = "id") Long id) {
        ServiceResult result = this.houseService.removePhoto(id);

        if (result.isSuccess()) {
            return Response.ofStatus(Response.Status.SUCCESS);
        } else {
            return Response.ofMessage(HttpStatus.BAD_REQUEST.value(), result.getMessage());
        }
    }

    /**
     * 修改封面接口
     * @param coverId
     * @param targetId
     * @return
     */
    @PostMapping("/house/cover")
    @ResponseBody
    public Response updateCover(@RequestParam(value = "cover_id") Long coverId,
                                   @RequestParam(value = "target_id") Long targetId) {
        ServiceResult result = this.houseService.updateCover(coverId, targetId);

        if (result.isSuccess()) {
            return Response.ofStatus(Response.Status.SUCCESS);
        } else {
            return Response.ofMessage(HttpStatus.BAD_REQUEST.value(), result.getMessage());
        }
    }

    /**
     * 增加标签接口
     * @param houseId
     * @param tag
     * @return
     */
    @PostMapping("/house/tag")
    @ResponseBody
    public Response addHouseTag(@RequestParam(value = "house_id") Long houseId,
                                   @RequestParam(value = "tag") String tag) {
        if (houseId < 1 || StringUtils.isBlank(tag)) {
            return Response.ofStatus(Response.Status.BAD_REQUEST);
        }

        ServiceResult result = this.houseService.addTag(houseId, tag);
        if (result.isSuccess()) {
            return Response.ofStatus(Response.Status.SUCCESS);
        } else {
            return Response.ofMessage(HttpStatus.BAD_REQUEST.value(), result.getMessage());
        }
    }

    /**
     * 移除标签接口
     * @param houseId
     * @param tag
     * @return
     */
    @DeleteMapping("/house/tag")
    @ResponseBody
    public Response removeHouseTag(@RequestParam(value = "house_id") Long houseId,
                                      @RequestParam(value = "tag") String tag) {
        if (houseId < 1 || StringUtils.isBlank(tag)) {
            return Response.ofStatus(Response.Status.BAD_REQUEST);
        }

        ServiceResult result = this.houseService.removeTag(houseId, tag);
        if (result.isSuccess()) {
            return Response.ofStatus(Response.Status.SUCCESS);
        } else {
            return Response.ofMessage(HttpStatus.BAD_REQUEST.value(), result.getMessage());
        }
    }

    /**
     * 审核接口
     * @param id
     * @param operation
     * @return
     */
    @PutMapping("/house/operate/{id}/{operation}")
    @ResponseBody
    public Response operateHouse(@PathVariable(value = "id") Long id,
                                    @PathVariable(value = "operation") int operation) {
        if (id <= 0) {
            return Response.ofStatus(Response.Status.NOT_VALID_PARAM);
        }
        ServiceResult result;

        switch (operation) {
            case HouseOperation.PASS:
                result = this.houseService.updateStatus(id, HouseStatus.PASSES.getValue());
                break;
            case HouseOperation.PULL_OUT:
                result = this.houseService.updateStatus(id, HouseStatus.NOT_AUDITED.getValue());
                break;
            case HouseOperation.DELETE:
                result = this.houseService.updateStatus(id, HouseStatus.DELETED.getValue());
                break;
            case HouseOperation.RENT:
                result = this.houseService.updateStatus(id, HouseStatus.RENTED.getValue());
                break;
            default:
                return Response.ofStatus(Response.Status.BAD_REQUEST);
        }

        if (result.isSuccess()) {
            return Response.ofSuccess(null);
        }
        return Response.ofMessage(HttpStatus.BAD_REQUEST.value(),
                result.getMessage());
    }


    @RequestMapping("/center")
    public String adminCenterPage() {
        return "admin/center";
    }

    @RequestMapping("/welcome")
    public String welcomePage() {
        return "admin/welcome";
    }

    @RequestMapping("/login")
    public String adminLoginPage() {
        return "admin/login";
    }

    @GetMapping("/add/house")
    public String addHouse() {
        return "admin/house-add";
    }

    @GetMapping("/house/list")
    public String houseListPage() {
        return "admin/house-list";
    }



}
